#define _CRT_SECURE_NO_WARNINGS 1

#include"Heap.h"

void HPInit(HP* php)
{
	assert(php);
	php->arr = NULL;
	php->capacity = php->size = 0;
}

void HPDestory(HP* php)
{
	assert(php);
	free(php->arr);
	php->arr = NULL;
	php->capacity = php->size = 0;
}

void HPPush(HP* php, HPDataType x)
{
	assert(php);

	if (php->size == php->capacity)
	{
		php->capacity = (php->capacity == 0) ? 4 : 2 * php->capacity;
		HPDataType* tmp = (HPDataType*)realloc(php->arr, php->capacity * sizeof(HPDataType));
		if (tmp == NULL)
		{
			perror("realloc");
			exit(1);
		}
		php->arr = tmp;
	}
	php->arr[php->size] = x;
	php->size++;

	AdjustUp(php->arr, php->size - 1);
}

void HPPop(HP* php)
{
	assert(php);
	assert(php->size > 0);

	Swap(&php->arr[php->size - 1], &php->arr[0]);
	php->size--;
	AdjustDown(php->arr, php->size, 0);
	
}

void AdjustUp(HPDataType* arr, int child)
{
	int parent = (child - 1) / 2;

	while (child > 0)
	{
		if (arr[child] < arr[parent])
		{
			Swap(&arr[child], &arr[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

void Swap(HPDataType* p1, HPDataType* p2)
{
	HPDataType tmp = *p1;
	*p1 = *p2;
	*p2 = tmp;
}

void AdjustDown(HPDataType* arr, int size, int parent)
{
	int child = 2 * parent + 1;

	while (child < size)
	{
		if ((child + 1) < size && arr[child] > arr[child + 1])
		{
			child++;
		}
		if (arr[parent] > arr[child])
		{
			Swap(&arr[parent], &arr[child]);
			parent = child;
			child = parent * 2 + 1;
		}
		else
		{
			break;
		}
	}
}

HPDataType HPTop(HP* php)
{
	assert(php);
	assert(php->size > 0);

	return php->arr[0];
}

bool HPEmpty(HP* php)
{
	assert(php);

	return php->size == 0;
}